<!--订单列表页-->
<template>
    <div style="height: 100%;">
        <m-page-list
                :option="option"
                :page="page"
                :total="total"
                :table-data="tableData"
                :table-loading="tableLoading"
                :page-loading="pageLoading"
                v-model:value="query"
                @h-btn-click="hBtnClick"
                @col-btn-click="colBtnClick"
                @search-data="searchData"
                @sort-data="sortData"
        />
        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>
        <m-dialog-form ref="mDialogRef" :data="mDialog.data" v-model:show="mDialogShow" :option="mDialog" @confirm="handleConfirm" ></m-dialog-form>

        <m-dialog-form :data="detailData" v-model:show="detailShow" :option="detailDialog" :readonly="true" @confirm="detailShow = false"></m-dialog-form>
    </div>

</template>

<script setup>

  import {ref,reactive,onMounted,nextTick} from 'vue'
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  import MDialogDetail from '@/components/DialogForm/DialogDetail'
  //请求
  import {getOrder, addOrder,editOrder,delOrder,getExportOrder,getPassengerBySchoolAndMonth,getPassengerGoToSchool,getPassengerLeaveSchool,getPassengerPhoto,orderRefund,orderRefund2} from '@/request/api/basicData'

  import {usePageList} from "../../composables/pageList";
  import {useRouteQuery} from "../../composables/routeQuery";
  //引用类型字段参数
  import {refOpt} from "../const";
  import {downFile} from "../../utils/utils";
  import {getAuthority} from "../../utils/permission";

  const opts = {
    pageSize: 10,
    auth_id: 'order',
    getApi: getOrder,addApi:addOrder,editApi:editOrder,delApi:delOrder,
    idKey: 'out_trade_no',
    stopMounted: true,
    baseQuery:{orderBy: 'success_time desc',returnAggregate:true},
    total: [
      {title: '售票数量',field_id:'count', value: 0},
      {title: '售票金额',field_id:'sum', value: 0},
    ],
    totalField: 'aggregate'
  };
  let {option,page,total,pageLoading,tableLoading,tableData,query,sort,dialogRef,dialogShow,dialogData,dialogOption,
    hBtnClick,colBtnClick,searchData,getDataList,dialogConfirm} = usePageList(opts);

  useRouteQuery(onRouteQueryChange);

  option.hLBtns = [];
  option.conditions = [
    {label: '乘车人名称',type: 'text',field_id: 'passengers_name'},
    {label: '监护人手机',type: 'text',field_id: 'guardian_phone'},
    {label: '购票人手机',type: 'text',field_id: 'phone'},
    {label: '班车类型',type: 'picklist',field_id: 'shuttle_type',col: 8,options: [
      {name: '车站客运班车',id: '车站客运班车'},
      {name: '定制',id: '定制'},
      ]},
    {label: '订单状态',type: 'picklist',field_id: 'order_status_list',col: 16,options: [
      {name: '待支付',id: '待支付'},
      {name: '已支付',id: '已支付'},
      {name: '已退票',id: '已退票'},
      {name: '申请退款中',id: '申请退款中'},
      {name: '购票失败',id: '购票失败'},
      {name: '已支付+申请退款中',id: '已支付,申请退款中'},
      ]},
    // {label: '套票标签名称',type: 'text',field_id: 'packag_label_name'},
    {...refOpt.packag_label_name,label: '套票标签',col: 8,rewriteInput: true},
    {...refOpt.school_name,rewriteInput: true,col: 8},
    {label: '班车名称',type: 'text',field_id: 'shuttle_name'},
    {label: '订单时间',type: 'datetimerange',field_id: ['order_create_time_range.begin_time','order_create_time_range.end_time'],col: 8},
    {label: '乘车月份',type: 'month',field_id: 'by_month',length: 'YYYYMM',col: 8},
    // {label: '站点名称',type: 'text',field_id: 'school_name'},
    {label: '班车编号',type: 'text',field_id: 'shuttle_id',col: 8},
  ];
  option.cols = [
    {prop: 'Order_status', label: '订单状态',fixed: 'left',customSort: true},
    {prop: 'passengers_name', label: '乘车人名称',fixed: 'left',customSort: true},
    {prop: 'pictures_link',label: '照片',type: 'picture',hidePic: true,fixed: 'left' },
    {prop: 'shuttle_name', label: '班车名称',customSort: true},
    {prop: 'shuttle_type', label: '班车类型',customSort: true},
    {prop: 'Order_refund_time',label: '申请退票时间' ,customSort: true},
    {prop: 'seat_no',label: '去程座',customSort: true },
    {prop: 'seat_no_leave',label: '回程座',customSort: true },
    {prop: 'guardian_phone', label: '监护人手机',customSort: true},
    {prop: 'packag_type_name', label: '套票类型名称',customSort: true},
    {prop: 'ticket_typall_name',label: '票种名称' ,customSort: true},
    {prop: 'payer_total',label: '已支付金额' ,customSort: true},
    {prop: 'Order_refund_reason',label: '申请退票原因' ,customSort: true},
    {prop: 'effective_time_start',label: '车票有效时间起',customSort: true },
    {prop: 'effective_time_end',label: '车票有效时间止' ,customSort: true},
    {prop: 'shuttle_id', label: '班车编号',customSort: true},
    {prop: 'passengers_id', label: '乘车人编号',customSort: true},
    {prop: 'identification_type_name', label: '证件类型名称',customSort: true},
    {prop: 'identification_no', label: '证件号码',customSort: true,},
    {prop: 'class_', label: '班级',customSort: true,},
    {prop: 'school_id',label: '站点编号',customSort: true },
    {prop: 'school_name',label: '站点名称',customSort: true },
    {prop: 'up_stop_name',label: '上车站点名称',customSort: true,templte: (scope) =>{
      let {up_departure_time,up_stop_name} = scope.row;
      return `${up_departure_time ? up_departure_time : ''} ${up_stop_name ? up_stop_name : ''}`
      } },
    {prop: 'down_stop_name',label: '下车站点名称',customSort: true,templte: (scope) =>{
        let {down_arrive_time,down_stop_name} = scope.row;
        return `${down_arrive_time ? down_arrive_time : ''} ${down_stop_name ? down_stop_name :''}`
      }  },
    {prop: 'Order_amount',label: '订单金额',customSort: true },
    {prop: 'success_time',label: '支付时间',customSort: true},
    {prop: 'out_trade_no',label: '订单号',customSort: true },
    {prop: 'transaction_id',label: '微信支付流水号',customSort: true },
    {prop: 'Order_create_time',label: '订单创建时间',customSort: true },
    {prop: 'mark',label: '说明' ,customSort: true},
    {prop: 'ticket_typall_id',label: '票种编号',customSort: true },
    {prop: 'customer_id',label: '客户编号' ,customSort: true},
    {prop: 'customer_name',label: '客户名称',customSort: true },
    {prop: 'phone',label: '客户手机' ,customSort: true},
    {prop: 'agreement_handwritten_pic',label: '签名照片',type: 'picture',hidePic: true,},
    {prop: 'agreement_all_pic',label: '协议照片',type: 'picture',hidePic: true},
    {prop: 'input_id',label: '录入员号' ,customSort: true},
    {prop: 'input_name',label: '录入员名',customSort: true },
    {prop: 'input_time',label: '录入时间',customSort: true },
    {prop: 'modify_id',label: '修改员号',customSort: true },
    {prop: 'modify_name',label: '修改员名',customSort: true },
    {prop: 'modify_time',label: '修改时间' ,customSort: true},
    {prop: 'refund_total_amount',label: '退款累计金额',customSort: true },
    {prop: 'refund_total_times',label: '退款累计次数',customSort: true },
    {prop: 'refund_last_time',label: '退款最后时间',customSort: true },
    {prop: 'refund_last_refund_no',label: '退款最后退款单号',customSort: true },
    {prop: 'refund_last_user_id',label: '退款最后操作员号',customSort: true },
    {prop: 'refund_last_user_name',label: '退款最后操作员名',customSort: true },
  ];
  dialogOption.fieldList = [
    {field_id: 'passengers_name', label: '乘车人名称',type: 'text',col: 2},
    {...refOpt.identification_type_id,col: 2},
    {...refOpt.identification_type_name,col: 2},
    {field_id: 'identification_no', label: '证件号码',type: 'text',col: 2},
    {field_id: 'guardian_phone', label: '监护人手机',type: 'text',col: 2},
    {field_id: 'class_', label: '班级',col: 2,type: 'text'},
    {field_id: 'pictures_link', label: '照片',col: 4,type: 'picture',limit: 1},
    // {...refOpt.ticket_typall_id,col: 2},
    // {...refOpt.ticket_typall_name,col: 2},
    // {field_id: 'effective_time_start',label: '班车有效时间起',type:'datetime',col: 2 },
    // {field_id: 'effective_time_end',label: '班车有效时间止',type:'datetime',col: 2 },
  ];

  option.showTotal = true;
  /*total = [
    {title: '售票数量',field_id:'count', value: 0},
    {title: '售票金额',field_id:'sum', value: 0},
  ];*/
  // option.hLBtns = [];
  /*option.hRBtns.unshift(
  {title: '导出订单',id: '',type: 'primary', event: () => exportFile('order')},
  // {title: '导出照片',id: '',type: 'primary', event: () => handleShow('picture')},
  {title: '导出照片',id: '',type: 'primary', event: () => exportFile('photo')},
  {title: '导出站点总名单',id: '',type: 'primary', event: () => handleShow('school')},
  {title: '导出班车去程名单',id: '',type: 'primary', event: () => handleShow('go')},
  {title: '导出班车回程名单',id: '',type: 'primary', event: () => handleShow('leave')},
  )*/

  option.colBtns.pop(); // 删除最后一个默认数据行操作按钮
  option.colBtns.push({title: '详情',type: 'primary', event: showDetail});    // 表格数据行操作
  query.value = {order_status_list: '已支付,申请退款中'}    //初始默认查询条件

  prepare();

  // 弹窗配置
  const dialogs = {
    order: {
      title: '导出订单',
      fieldList: [
        {...refOpt.school_name, col: 3},
        {field_id: 'yearMonth', label: '年月', type: 'month',dateFormat: 'YYYYMM', col: 3,},
      ],
      data: {}
    },
    picture: {
      title: '导出照片',
      fieldList: [
        {...refOpt.school_name, col: 3,required: true},
        {field_id: 'yearMonth', label: '年月', type: 'month',dateFormat: 'YYYYMM', col: 3,},
      ],
      data: {}
    },
    school: {
      title: '导出站点总名单',
      fieldList: [
        {...refOpt.school_name, col: 3,required: true},
        {field_id: 'yearMonth', label: '年月', type: 'month',dateFormat: 'YYYYMM', col: 3,},
      ],
      data: {}
    },
    go: {
      title: '导出班车去程名单',
      fieldList: [
        // {...refOpt.school_name, col: 3},
        {...refOpt.shuttle_name, col: 3},
        {field_id: 'yearMonth', label: '年月', type: 'month',dateFormat: 'YYYYMM', col: 3,},
      ],
      data: {}
    },
    leave: {
      title: '导出班车回程名单',
      fieldList: [
        // {...refOpt.school_name, col: 3},
        {...refOpt.shuttle_name, col: 3},
        {field_id: 'yearMonth', label: '年月', type: 'month',dateFormat: 'YYYYMM', col: 3,},
      ],
      data: {}
    },
    refund: {
      title: '退款',
      fieldList: [
        {field_id: 'out_trade_no', label: '订单号',type: 'text', disabled: true, col: 3},
        {field_id: 'refund_amount', label: '退款金额',type: 'number', precision: 2, col: 3,required: true},
      ],
      data: {}
    },
    initiativeRefund: {
      title: '主动退款',
      fieldList: [
        {field_id: 'out_trade_no', label: '订单号',type: 'text', disabled: true, col: 3},
        {field_id: 'refund_amount', label: '退款金额',type: 'number', precision: 2, col: 3,required: true},
        {field_id: 'Order_refund_reason', label: '退款原因',type: 'textarea', col: 3,},
      ]
    }
  },
    mDialog = ref({}),
    mDialogShow = ref(false),
    mDialogRef = ref(null);

  //详细数据
  const detailDialog = {
    title: '详情',
    center: true,
    fieldList: [
      {field_id: 'Order_status', label: '订单状态',fixed: 'left',type: 'text',disabled: true,col: 2},
      {field_id: 'passengers_name', label: '乘车人名称',fixed: 'left',type: 'text',disabled: true,col: 2},
      {field_id: 'pictures_link',label: '照片',type: 'picture',hidePic: true,fixed: 'left' ,disabled: true,col: 2},
      {field_id: 'shuttle_name', label: '班车名称',type: 'text',disabled: true,col: 2},
      {field_id: 'seat_no',label: '去程座' ,type: 'text',disabled: true,col: 2},
      {field_id: 'seat_no_leave',label: '回程座' ,type: 'text',disabled: true,col: 2},
      {field_id: 'shuttle_type', label: '班车类型',type: 'text',disabled: true,col: 2},
      {field_id: 'guardian_phone', label: '监护人手机',type: 'text',disabled: true,col: 2},
      {field_id: 'agreement_handwritten_pic',label: '签名照片',type: 'picture',hidePic: true,fixed: 'left' ,disabled: true,col: 2},
      {field_id: 'agreement_all_pic',label: '协议照片',type: 'picture',hidePic: true,fixed: 'left' ,disabled: true,col: 2},
      {field_id: 'packag_type_name', label: '套票类型名称',type: 'text',disabled: true,col: 2},
      {field_id: 'ticket_typall_name',label: '票种名称' ,type: 'text',disabled: true,col: 2},
      {field_id: 'payer_total',label: '已支付金额' ,type: 'text',disabled: true,col: 2},
      {field_id: 'Order_refund_time',label: '申请退票时间' ,type: 'text',disabled: true,col: 2},
      {field_id: 'Order_refund_reason',label: '申请退票原因' ,type: 'text',disabled: true,col: 4},
      {field_id: 'effective_time_start',label: '车票有效时间起' ,type: 'text',disabled: true,col: 2},
      {field_id: 'effective_time_end',label: '车票有效时间止' ,type: 'text',disabled: true,col: 2},
      {field_id: 'shuttle_id', label: '班车编号',type: 'text',disabled: true,col: 2},
      {field_id: 'passengers_id', label: '乘车人编号',type: 'text',disabled: true,col: 2},
      {field_id: 'identification_type_name', label: '证件类型名称',type: 'text',disabled: true,col: 2},
      {field_id: 'identification_no', label: '证件号码',type: 'text',disabled: true,col: 2},
      {field_id: 'class_', label: '班级',type: 'text',disabled: true,col: 2},
      {col: 2},
      {field_id: 'school_id',label: '站点编号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'school_name',label: '站点名称' ,type: 'text',disabled: true,col: 2},
      {field_id: 'up_stop_name',label: '上车站点名称' ,type: 'text',disabled: true,col: 2},
      {field_id: 'down_stop_name',label: '下车站点名称' ,type: 'text',disabled: true,col: 2},
      {field_id: 'Order_amount',label: '订单金额' ,type: 'text',disabled: true,col: 2},
      {field_id: 'success_time',label: '支付时间',type: 'text',disabled: true,col: 2},
      {field_id: 'out_trade_no',label: '订单号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'transaction_id',label: '微信支付流水号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'Order_create_time',label: '订单创建时间' ,type: 'text',disabled: true,col: 2},
      {field_id: 'mark',label: '说明' ,type: 'text',disabled: true,col: 4},
      {field_id: 'ticket_typall_id',label: '票种编号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'customer_id',label: '客户编号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'customer_name',label: '客户名称' ,type: 'text',disabled: true,col: 2},
      {field_id: 'phone',label: '客户手机' ,type: 'text',disabled: true,col: 2},
      {field_id: 'input_id',label: '录入员号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'input_name',label: '录入员名' ,type: 'text',disabled: true,col: 2},
      {field_id: 'input_time',label: '录入时间' ,type: 'text',disabled: true,col: 2},
      {field_id: 'modify_id',label: '修改员号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'modify_name',label: '修改员名' ,type: 'text',disabled: true,col: 2},
      {field_id: 'modify_time',label: '修改时间' ,type: 'text',disabled: true,col: 2},
      {field_id: 'refund_total_amount',label: '退款累计金额' ,type: 'text',disabled: true,col: 2},
      {field_id: 'refund_total_times',label: '退款累计次数' ,type: 'text',disabled: true,col: 2},
      {field_id: 'refund_last_time',label: '退款最后时间' ,type: 'text',disabled: true,col: 2},
      {field_id: 'refund_last_refund_no',label: '退款最后退款单号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'refund_last_user_id',label: '退款最后操作员号' ,type: 'text',disabled: true,col: 2},
      {field_id: 'refund_last_user_name',label: '退款最后操作员名' ,type: 'text',disabled: true,col: 2},
    ]
  },
    detailShow = ref(false),
    detailData = ref({});

  function developing() {
    ElMessage({
      type: 'warning',
      message: '功能正在开发中'
    })
  }
  //退票
  function refund(param) {

    ElMessage({
      type: 'warning',
      message: '功能正在开发中'
    })
    //退票
    return new Promise(resolve => {
      resolve();
    })
  }

  //路由参数变化执行查询数据
  function onRouteQueryChange(routeQuery){
    query.value = { ...query.value,shuttle_id: '',...routeQuery};
    getDataList();
  }

  //显示弹窗
  function handleShow(id,scope) {
    if (id === 'refund' || id === 'initiativeRefund') {
      let {payer_total,out_trade_no} = scope.row
      dialogs[id].data = {refund_amount: payer_total,out_trade_no}
    }

    mDialog.value = dialogs[id];
    mDialogShow.value = true
  }
//  弹窗确认
  function handleConfirm(obj) {
    let {data,option} = obj;
    new Promise(resolve => {
      // if (option.title === '导出订单') {}
      // else if (option.title === '导出照片') getPassengerPhoto(data).then(() => resolve())
      if (option.title === '导出站点总名单') {
        delete data.school_name;
        getPassengerBySchoolAndMonth(data).then((res) => resolve(res))
      }
      else if (option.title === '导出班车去程名单') getPassengerGoToSchool(data).then((res) => resolve(res))
      else if (option.title === '导出班车回程名单') getPassengerLeaveSchool(data).then((res) => resolve(res))

    }).then((res) => {
      mDialogRef.value.close();
      let {data} = res;
      let filename = decodeURIComponent(res.headers["content-disposition"]);
      filename = filename?.split(`filename*=UTF-8''`)[1]
      downFile(data,filename);
    });
    if (option.title === '退款') {
      mDialogRef.value.close();
      pageLoading.value = true
      orderRefund(data).then((res) => {
        pageLoading.value = false
        if (res.errcode !== 0) return
        ElMessage({type: 'success',message: '退款成功'})
        getDataList();
      })
    }
    if (option.title === '主动退款'){
      mDialogRef.value.close();
      initiativeRefund(data);
    }
  }

  // 导出订单
  function exportOrder() {

  }
  // 导出乘车人照片
  function exportFile(id) {
    pageLoading.value = true;
    let api = id === 'photo' ? getPassengerPhoto : getExportOrder;

    api(query.value).then(res => {
      pageLoading.value = false;
      let {data} = res;
      let filename = decodeURIComponent(res.headers["content-disposition"]);
      filename = filename?.split(`filename*=UTF-8''`)[1]
      downFile(data, filename);
    })
  }

  //显示详细数据
  function showDetail(scope){
    detailData.value = scope.row;
    detailShow.value = true;

  }

  function prepare (){
    //导出权限
    let exportOrder = getAuthority('exportOrder'),
      exportPhoto = getAuthority('exportPhoto'),
      exportSchool = getAuthority('exportSchool'),
      exportGo = getAuthority('exportGo'),
      exportLeave = getAuthority('exportLeave'),
      order_refund = getAuthority('order_refund');

    let arr = [];
    exportOrder.is_see && arr.push({title: '导出订单',id: '',type: 'primary', event: () => exportFile('order')})
    exportPhoto.is_see && arr.push({title: '导出照片',id: '',type: 'primary', event: () => exportFile('photo')})
    exportSchool.is_see && arr.push({title: '导出站点总名单',id: '',type: 'primary', event: () => handleShow('school')})
    exportGo.is_see && arr.push({title: '导出班车去程名单',id: '',type: 'primary', event: () => handleShow('go')})
    exportLeave.is_see && arr.push({title: '导出班车回程名单',id: '',type: 'primary', event: () => handleShow('leave')})
    option.hRBtns.unshift(...arr);

    order_refund.is_see && option.colBtns.push({title: '退款',id: 'check',type: 'warning',
      filterMethod: (scope) => scope.row.Order_status === '申请退款中',
      event: (scope) => handleShow('refund',scope) },
      {
        title: '主动退款',
        type: 'warning',
        filterMethod: (scope) => scope.row.Order_status === '已支付',
        event: scope => handleShow('initiativeRefund',scope)
      }
    )
  }

  //排序
  function sortData(query){
    sort.value = query ? query : {}
    getDataList();
  }

  // 主动退款
  function initiativeRefund(data) {
    pageLoading.value = true;
    data.Order_refund_reason = data.Order_refund_reason || '主动退款';
    orderRefund2(data).then((res) => {
      pageLoading.value = false
      if (res.errcode !== 0) return
      ElMessage({type: 'success',message: '退款成功'})
      getDataList();
    })
  }


</script>

<style scoped lang="less">

</style>
